<?php


namespace App\Http\Controllers\Admin;
use App\Exports\CommissionedExport;
use App\Models\CommissionedRecruit;
use Dingo\Api\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class CommissionedRecruitController extends BaseController
{

    public function index(Request $request) {
        $this->validate($request, [
            'status' => 'filled|in:0,1,2',
        ]);
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');
        $status = $request->input('status');
        $is_export = $request->input('is_export', false);
        if ($is_export) {
            $limit = 50000;
        } else {
            $limit = $request->get('per_page',20);
        }

        $list = CommissionedRecruit::when($start_at, function ($q) use($start_at){
            $q->where('created_at', '>=', $start_at);
        })->when($end_at, function ($q) use($end_at){
            $end_at = date('Y-m-d', strtotime($end_at) + 24 * 3600);
            $q->where('created_at', '<=', $end_at);
        })->withCertain('role', ['value'])
            ->withCertain('admin', ['username'])
            ->when($status, function ($q) use($status){
            $q->where('status', $status);
        })->orderBy("id", "desc")->paginate($limit);

        if ($is_export) {
            $res = $list->toArray();
            return Excel::download(new CommissionedExport($res['data']),  "委托招聘列表.xlsx");
        }
        return $this->paginate($list);
    }



    public function setStatus(Request $request) {
        $this->validate($request, [
            'ids' => 'required',
        ]);
        $ids = $request->input("ids");
        $arr_id = explode(",", $ids);
        CommissionedRecruit::whereIn('id', $arr_id)->update([
            'status' => CommissionedRecruit::STATUS_FINISH,
            'admin_id' => $this->getUser()->id
        ]);
        return $this->success(['id' => $ids]);
    }


}

